let that
let request = require('../../operation/operation.js')
let bxt = require('../../utils/bxt.js')
let noticeModel = require('../../models/notice.js')

function show(source) {
  that = source
  let dialogComponent = that.selectComponent('.wxc-dialog')
  dialogComponent && dialogComponent.show();
}

function cancel() {
  let dialogComponent = that.selectComponent('.wxc-dialog')
  dialogComponent && dialogComponent.hide();
}

function initRate(reviewResult, flowerCount,content='') {
  let rate = false
  if (noticeModel.REVIEW_RESULT.PASS == reviewResult) {
    rate = true
  }

  that.setData({
      rate:rate,
      content:content,
      flowerCount: flowerCount     
  })
}

function setFlowerCount(flowerCount) {
  that.setData({
    flowerCount: flowerCount
  })
}

/**
 * 创建批改
 */
function createReview(receiptSid, result, content, flowerCount) {
  let params = { 'receiptSid': receiptSid, 'result': result, "flowerCount": flowerCount}
  if (content && '' != content) {
    params.content = content
  }else {
    params.content = ''
  }

  return new Promise((resolve, reject) => {
    request.startRequest('POST', '/reviews', params, true)
      .then(res => {       
        let data = res.data
        if (request.SUCCESSED == data.status) {
          wx.showToast({
            title: '批改完成',
            icon: "success"
          })
          
          let reviewObject = data.object          
          resolve(reviewObject)
        } else {
          wx.showToast({
            title: data.msg,
            icon: 'none'
          })
        }
      })
      .catch(e => {        
        wx.showToast({
          title: e,
          icon: 'none'
        })
      })
  })
}

/**
 * 更新批改
 */
function updateReview(reviewId, result, content,flowerCount) {
  let params = { 'result': result, 'flowerCount': flowerCount }
  if (content && '' != content) {
    params.content = content
  } else {
    params.content = ''
  }

  return new Promise((resolve, reject) => {
    request.startRequest('PUT', '/reviews/' + reviewId, params, true)
      .then(res => {
        let data = res.data
        if (request.SUCCESSED == data.status) {         
          let reviewObject = data.object
          resolve(reviewObject)
        } else {
          wx.showToast({
            title: data.msg,
            icon: 'none'
          })
        }
      })
      .catch(e => {
        wx.showToast({
          title: e,
          icon: 'none'
        })
      })
  })
}

module.exports = {
  cancel: cancel,
  show: show,
  createReview: createReview,
  updateReview: updateReview,
  initRate:initRate,
  setFlowerCount: setFlowerCount
}